package org.jeecg.modules.demo.ch.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ch.Utils.OrderBomUtils;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChDesignBomExcel;
import org.jeecg.modules.demo.ch.entity.ChDesignBomMaster;
import org.jeecg.modules.demo.ch.entity.ChParameter;
import org.jeecg.modules.demo.ch.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 模具设计BOM导入EXCEL表
 * @Author: jeecg-boot
 * @Date: 2022-09-23
 * @Version: V1.0
 */
@Api(tags = "模具设计BOM导入EXCEL表")
@RestController
@RequestMapping("/ch/chDesignBomExcel")
@Slf4j
public class ChDesignBomExcelController extends JeecgController<ChDesignBomExcel, IChDesignBomExcelService> {
    @Autowired
    private IChDesignBomExcelService iChDesignBomExcelService;

    @Autowired
    private IChDesignBomMasterService iChDesignBomMasterService;

    @Autowired
    private IChDesignBomDetailService iChDesignBomDetailService; //设计BOM

    @Autowired
    private IChOrderBomService iChOrderBomService; //设计BOM

    @Autowired
    private IChParameterService iChParameterService;



    /**
     * 分页列表查询
     *
     * @param chDesignBomExcel
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "模具设计BOM导入EXCEL表-分页列表查询")
    @ApiOperation(value = "模具设计BOM导入EXCEL表-分页列表查询", notes = "模具设计BOM导入EXCEL表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ChDesignBomExcel>> queryPageList(ChDesignBomExcel chDesignBomExcel,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<ChDesignBomExcel> queryWrapper = QueryGenerator.initQueryWrapper(chDesignBomExcel, req.getParameterMap());
        Page<ChDesignBomExcel> page = new Page<>(pageNo, pageSize);
        IPage<ChDesignBomExcel> pageList = iChDesignBomExcelService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param chDesignBomExcel
     * @return
     */
    @AutoLog(value = "模具设计BOM导入EXCEL表-添加")
    @ApiOperation(value = "模具设计BOM导入EXCEL表-添加", notes = "模具设计BOM导入EXCEL表-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom_excel:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ChDesignBomExcel chDesignBomExcel) {
        iChDesignBomExcelService.save(chDesignBomExcel);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param chDesignBomExcel
     * @return
     */
    @AutoLog(value = "模具设计BOM导入EXCEL表-编辑")
    @ApiOperation(value = "模具设计BOM导入EXCEL表-编辑", notes = "模具设计BOM导入EXCEL表-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom_excel:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ChDesignBomExcel chDesignBomExcel) {
        iChDesignBomExcelService.updateById(chDesignBomExcel);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "模具设计BOM导入EXCEL表-通过id删除")
    @ApiOperation(value = "模具设计BOM导入EXCEL表-通过id删除", notes = "模具设计BOM导入EXCEL表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom_excel:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        iChDesignBomExcelService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "模具设计BOM导入EXCEL表-批量删除")
    @ApiOperation(value = "模具设计BOM导入EXCEL表-批量删除", notes = "模具设计BOM导入EXCEL表-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom_excel:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.iChDesignBomExcelService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "模具设计BOM导入EXCEL表-通过id查询")
    @ApiOperation(value = "模具设计BOM导入EXCEL表-通过id查询", notes = "模具设计BOM导入EXCEL表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ChDesignBomExcel> queryById(@RequestParam(name = "id", required = true) String id) {
        ChDesignBomExcel chDesignBomExcel = iChDesignBomExcelService.getById(id);
        if (chDesignBomExcel == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(chDesignBomExcel);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param chDesignBomExcel
     */
    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom_excel:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ChDesignBomExcel chDesignBomExcel) {
        return super.exportXls(request, chDesignBomExcel, ChDesignBomExcel.class, "模具设计BOM导入EXCEL表");
    }

//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    //@RequiresPermissions("ch_design_bom_excel:importExcel")
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, ChDesignBomExcel.class);
//    }


    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();//获取文件的名称
        String name = file.getName();
        log.info("filename:{},name:{}", filename, name);

        ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
        //获取表头部分
        //objects:[模具编码:CH2022001D, 模具编码:CH2022001D, 模具编码:CH2022001D, 客户:ZEBRA, 产品编号:HN-001982-32, 产品编号:HN-001982-32, 产品编号:HN-001982-32, 版本:V1.0]
        List<List<Object>> readAll = excelReader.read(1, 1);
        if (readAll.size() == 0) {
            return Result.error("文件内容为空!");
        }
        ChDesignBomMaster chDesignBomMaster = savaChDesignBomMaster(readAll);
        //根据模具编码判断是更新or新增
        LambdaQueryWrapper<ChDesignBomMaster> chDesignBomMasterLambdaQueryWrapper = new QueryWrapper<ChDesignBomMaster>().lambda();
        chDesignBomMasterLambdaQueryWrapper.eq(ChDesignBomMaster::getMoldCode, chDesignBomMaster.getMoldCode());
        ChDesignBomMaster one = iChDesignBomMasterService.getOne(chDesignBomMasterLambdaQueryWrapper);
        if (one == null) {//新增
            iChDesignBomMasterService.save(chDesignBomMaster);
        } else {
            //修改
            chDesignBomMaster.setId(one.getId());
            iChDesignBomMasterService.updateById(chDesignBomMaster);
        }

        // 3.读取第三行到最后一行数据
        List<List<Object>> read = excelReader.read(3, excelReader.getRowCount());
        if (read.size() == 0) {
            return Result.error("设计BOM明细数据为空!");
        }

        LambdaQueryWrapper<ChParameter> chParameterLambdaQueryWrapper = new QueryWrapper<ChParameter>().lambda();
        chParameterLambdaQueryWrapper.eq(ChParameter::getMajorCategories, CommonMst.ORDER_BOM.DESIGN_BOM);
        chParameterLambdaQueryWrapper.eq(ChParameter::getLittleClass, CommonMst.ORDER_BOM.VERSION);
        ChParameter chParameter = iChParameterService.getOne(chParameterLambdaQueryWrapper);
        if (chParameter == null) {
            throw new RuntimeException("根据大类小类未查询到设计BOM版本");
        }
        ArrayList<ChDesignBomExcel> chDesignBomExcels = new ArrayList<>();
        for (List<Object> objectList : read) {
            // objects.get(0),读取某行第一列数据
            //objectList:[序号, 零件名, 中文名, 英文名, 零件规格, 材料, 数量, 备注]
            //objectList:[1, MP, 模胚, MOULDBASE, CI5070A220B140C170, STD , 1, LKM
            ChDesignBomExcel chDesignBomExcel = new ChDesignBomExcel();
            chDesignBomExcel.setSerialNumber(OrderBomUtils.setStringIfNotNull(objectList.get(0)));//设置序号
            chDesignBomExcel.setPartName(OrderBomUtils.setStringIfNotNull(objectList.get(1)));//零件名
            chDesignBomExcel.setChineseName(OrderBomUtils.setStringIfNotNull(objectList.get(2)));//中文名
            chDesignBomExcel.setEnglishName(OrderBomUtils.setStringIfNotNull(objectList.get(3)));//英文名
            chDesignBomExcel.setPartSpecification(OrderBomUtils.setStringIfNotNull(objectList.get(4)));//零件规格
            chDesignBomExcel.setMaterial(OrderBomUtils.setStringIfNotNull(objectList.get(5)));//材料
            chDesignBomExcel.setNumber(OrderBomUtils.setIntegerIfNotNull(objectList.get(6)));//数量
            chDesignBomExcel.setRemark(OrderBomUtils.setStringIfNotNull(objectList.get(7)));//备注

            chDesignBomExcel.setChDesignBomMasterId(chDesignBomMaster.getId());//模具设计BOM主表id
            chDesignBomExcel.setVersion(chParameter.getValueStr());//版本
            chDesignBomExcels.add(chDesignBomExcel);
        }
        //先删除再增加
        LambdaQueryWrapper<ChDesignBomExcel> lambdaQueryWrapper = new QueryWrapper<ChDesignBomExcel>().lambda();
        lambdaQueryWrapper.eq(ChDesignBomExcel::getChDesignBomMasterId, chDesignBomMaster.getId());
        List<ChDesignBomExcel> list = iChDesignBomExcelService.list(lambdaQueryWrapper);
        if (list.size() > 0) {
            iChDesignBomExcelService.removeByIds(list);
        }
        iChDesignBomExcelService.saveBatch(chDesignBomExcels);
        log.info("chDesignBom:{}", chDesignBomExcels.size());

        return Result.OK("文件导入成功！");
    }

    /**
     * 保存头部部分
     *
     * @param readAll
     */
    public ChDesignBomMaster savaChDesignBomMaster(List<List<Object>> readAll) {
        //封装对象
        ChDesignBomMaster chDesignBomMaster = new ChDesignBomMaster();
        for (List<Object> objects : readAll) {
            for (Object object : objects) {
                String obj = String.valueOf(object);
                if (StringUtils.hasLength(obj) && obj.contains(CommonMst.ORDER_BOM.COLON)) {
                    String[] split = obj.split(CommonMst.ORDER_BOM.COLON);
                    if (split[0].equals(CommonMst.ORDER_BOM.MOLD_CODE)) {//模具编码
                        chDesignBomMaster.setMoldCode(split[1]);
                    }
                    ;
                    if (split[0].equals(CommonMst.ORDER_BOM.CUSTOMER)) {//客户
                        chDesignBomMaster.setCustomer(split[1]);
                    }
                    ;
                    if (split[0].equals(CommonMst.ORDER_BOM.PRODUCT_NO)) {//产品编号
                        chDesignBomMaster.setProductNo(split[1]);
                    }
                    ;
//					if (split[0].equals(CommonMst.ORDER_BOM.VERSION)){//版本
//						chDesignBomMaster.setVersion(split[1]);
//					};
                }
            }
        }
        log.info("封装的表头对象ChDesignBomMaster:{}", chDesignBomMaster);
        LambdaQueryWrapper<ChParameter> chParameterLambdaQueryWrapper = new QueryWrapper<ChParameter>().lambda();
        chParameterLambdaQueryWrapper.eq(ChParameter::getMajorCategories, CommonMst.ORDER_BOM.DESIGN_BOM);
        chParameterLambdaQueryWrapper.eq(ChParameter::getLittleClass, CommonMst.ORDER_BOM.VERSION);
        ChParameter chParameter = iChParameterService.getOne(chParameterLambdaQueryWrapper);
        if (chParameter == null) {
            throw new RuntimeException("根据大类小类未查询到设计BOM版本");
        }
        chDesignBomMaster.setVersion(chParameter.getValueStr());//版本

        return chDesignBomMaster;
    }


    /**
     * 通过excel导入数据（分批导入）
     *
     * @return
     */
    @RequestMapping(value = "/batchImportExcel", method = RequestMethod.GET)
    public Result<?> batchImportExcel(HttpServletRequest request, HttpServletResponse response) {
        LambdaQueryWrapper<ChDesignBomExcel> chDesignBomExcelLambdaQueryWrapper = new QueryWrapper<ChDesignBomExcel>().lambda();
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (!oConvertUtils.isNotEmpty(selections)) {
            return Result.error("请选择要分批导入的数据!");
        }

        List<String> selectionList = Arrays.asList(selections.split(","));
        chDesignBomExcelLambdaQueryWrapper.in(ChDesignBomExcel::getId, selectionList);

        List<ChDesignBomExcel> chDesignBomExcelList = iChDesignBomExcelService.list(chDesignBomExcelLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(chDesignBomExcelList)) {
            return Result.error("查询到的数据为空!");
        }
        //开始进行分批导入
        iChDesignBomExcelService.batchImportExcel(chDesignBomExcelList);
        return Result.ok("分批导入成功!");
    }


    /**
     * 通过excel导入数据（全部导入）
     *
     * @return
     */
    @RequestMapping(value = "/importAllExcel", method = RequestMethod.POST)
    public Result<?> importAllExcel(HttpServletRequest request, HttpServletResponse response, ChDesignBomMaster chDesignBomMaster) {
        String moldCode = chDesignBomMaster.getMoldCode();
        if (!StringUtils.hasLength(moldCode)) {
            return Result.error("传来的模具编码为空!不可全部导入");
        }
        LambdaQueryWrapper<ChDesignBomMaster> chDesignBomMasterLambdaQueryWrapper = new QueryWrapper<ChDesignBomMaster>().lambda();
        chDesignBomMasterLambdaQueryWrapper.eq(ChDesignBomMaster::getMoldCode, moldCode);
        ChDesignBomMaster bomMasterServiceOne = iChDesignBomMasterService.getOne(chDesignBomMasterLambdaQueryWrapper);
        if (bomMasterServiceOne == null) {
            return Result.error("传来的模具编码错误!根据传来的模具编码未找到该数据!");
        }
        //将ch_design_bom_excel表的数据 全部导入 ch_design_bom_detail 和 ch_order_bom中
        LambdaQueryWrapper<ChDesignBomExcel> chDesignBomExcelLambdaQueryWrapper = new QueryWrapper<ChDesignBomExcel>().lambda();
        chDesignBomExcelLambdaQueryWrapper.eq(ChDesignBomExcel::getChDesignBomMasterId, bomMasterServiceOne.getId());
        //过滤选中数据
        List<ChDesignBomExcel> chDesignBomExcelList = iChDesignBomExcelService.list(chDesignBomExcelLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(chDesignBomExcelList)) {
            return Result.error("根据模具设计BOM主表id查询到的数据为空!");
        }
        //开始进行全部导入
        iChDesignBomExcelService.importAllExcel(chDesignBomExcelList);
        return Result.ok("全部导入成功!");
    }

}
